package org.footito.android.data.update;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.util.ByteArrayBuffer;
import org.footito.android.data.Team;
import org.footito.android.tools.Log;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;

public class LoadAsyncTask extends AsyncTask<Void, Void, Void> {
	private String filePath;
	private String fileName;
	private Team team;

	public LoadAsyncTask(String filePath, String fileName, Team team) {
		this.filePath = filePath;
		this.fileName = fileName;
		this.team = team;
	}

	@Override
	protected Void doInBackground(Void... params) {
		try {
			URL url = new URL(team.getPictureLink());
			File file = new File(filePath, fileName);

			long startTime = System.currentTimeMillis();

			Log.d("Image Manager :" + "download begining");
			Log.d("Image Manager :" + "download url:" + url);
			Log.d("Image Manager :" + "downloaded file name:" + filePath + fileName);

			/* Open a connection to that URL. */
			URLConnection icon = url.openConnection();
			/*
			 * Define InputStreams to read from the URLConnection.
			 */

			InputStream is = icon.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);

			/*
			 * Read bytes to the Buffer until there is nothing more to read(-1).
			 */

			ByteArrayBuffer baf = new ByteArrayBuffer(50);
			int current = 0;
			while ((current = bis.read()) != -1) {
				baf.append((byte) current);
			}

			/* Convert the Bytes read to a String. */
			if (!file.exists())
				file.createNewFile();

			FileOutputStream fos = new FileOutputStream(file);
			fos.write(baf.toByteArray());
			fos.close();
			Log.d("Image Manager :" + "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");

			Bitmap bitmap = BitmapFactory.decodeFile(filePath + fileName);
			team.setPicture(bitmap);
		} catch (IOException e) {
			Log.d("Image Manager :" + "Error: line 524 DBAdapter" + e);
		} catch (StringIndexOutOfBoundsException e) {
			Log.d("Big url: " + team.getPictureLink());
		}

		return null;
	}

}